import { mapGetters, mapActions } from 'vuex'
import { themeList, addCss, reomveAllCss, getReadTimeByMinute } from './book'
import { saveLocation, getLocation, getBookmark, getBookShelf, saveBookShelf } from '@/utils/localStorage.js'
import { gotoBookDetail, appendAddToshelf, computedId, removeAddFromShelf } from './store'
import { shelf } from '../api/store'
export const storeShelfMixin = {
  computed: {
    ...mapGetters([
      'isEditMode',
      'shelfList',
      'shelfSelected',
      'shelfTitleVisible',
      'offsetY',
      'shelfCategory',
      'currentType'
    ])
  },
  methods: {
    ...mapActions([
      'setIsEditMode',
      'setShelfList',
      'setShelfSelected',
      'setShelfTitleVisible',
      'setOffsetY',
      'gotoBookDetail',
      'setShelfCategory',
      'setCurrentType'
    ]),
    moveOutOfGroup(f) {
      // 1 将选中的电子书移出  shelfCategory
      this.setShelfList(
        this.shelfList.map((books) => {
          if (books.itemList && books.type === 2) {
            // methods1
            // books.itemList = books.itemList.filter(subBook => this.shelfSelected.indexOf(subBook) < 0)
            // methods2
            books.itemList = books.itemList.filter(
              (subBook) => !subBook.selected
            )
          }
          return books
        })
      ).then(() => {
        // 将shelfList 中的 最后一个加号去掉
        // 合并数组
        // 将加号追加上
        /**
         * 这里还有很重要的步骤是去重新计算id
         * 因为我们的书架图书的顺序被改变了
         * 改变后要去重新计算id
         * 因为我们既有改动分组里面的数据也改动外面的数据
         * store.js 中定义方法 */
        const list = computedId(appendAddToshelf([].concat(removeAddFromShelf(this.shelfList), ...this.shelfSelected)))
        this.setShelfList(list).then(() => {
          this.simpleToast(this.$t('shelf.moveBookOutSuccess'))
          if (f) f()
        })
      })
    },
    getCategoryList(title) {
      this.getShelfList().then(() => {
        // 筛选
        const categorylList = this.shelfList.filter(book =>
          book.type === 2 && book.title === title
        )[0]
        this.setShelfCategory(categorylList)
        console.log(categorylList)
      })
    },
    // 获取数据 this
    getShelfList() {
      this.list = getBookShelf()
      if (this.list && this.list.length >= 2) {
        console.log(this.list)
        return this.setShelfList(this.list)
      } else {
        shelf().then((response) => {
          try {
            if (response.status === 200 &&
                  response.data &&
                  response.data.bookList
            ) {
              console.log('获取数据成功')
              const { data } = response
              this.list = data.bookList
              appendAddToshelf(this.list)
              saveBookShelf(this.list)
              // return 一个promise对象
              return this.setShelfList(this.list)
            } else {
              // return 一个promise对象
              return this.simpleToast('数获取失败')
            }
          } catch (error) {
            console.log(error)
          }
          console.log(this.list)
        })
      }
    }
  }
}
export const storeHomeMixin = {
  computed: {
    ...mapGetters([
      'offsetY',
      'hotSearchOffsetY',
      'flapCardVisible'
    ])
  },
  methods: {
    ...mapActions([
      'setOffsetY',
      'setHotSearchOffsetY',
      'setFlapCardVisible'
    ]),
    // 路由跳转
    showBookDetail(book) {
      gotoBookDetail(this, book)
    }
  }
}
export const ebookMixin = {
  computed: {
    ...mapGetters([
      'fileName',
      'menuVisible',
      'settingVisible',
      'defaultFontSize',
      'defaultFontFamily',
      'fontFamilyVisible',
      'defaultTheme',
      'bookAvailable',
      'progress',
      'section',
      'isPaginating',
      'currentBook',
      'navigation',
      'cover',
      'metadata',
      'paginate',
      'pagelist',
      'offsetY',
      'isBookmark',
      'ebookMark',
      'total'
    ]),
    themeList() {
      return themeList(this)
    },
    // 页眉
    getSectionName() {
      return this.section ? this.navigation[this.section].label : ''
    }
  },
  methods: {
    ...mapActions([
      'setFileName',
      'setMenuVisible',
      'setSettingVisible',
      'setDefaulfFontSize',
      'setDefaultFontFamily',
      'setFontFamilyVisible',
      'setDefaultTheme',
      'setBookAvailable',
      'setProgress',
      'setSection',
      'setIsPaginating',
      'setCurrentBook',
      'setNavigation',
      'setCover',
      'setMetadata',
      'setPaginate',
      'setPagelist',
      'setOffsetY',
      'setIsBookmark',
      'setEbookMark',
      'setTotal'
    ]),
    // 初始化全局样式
    initGlobalStyle() {
      // 去除重复得css文件
      reomveAllCss()
      // addCss('http://localhost:81/theme/theme_eye.css')
      // addCss(`${process.env.VUE_APP_RES_URL}/theme/theme_eye.css`)
      switch (this.defaultTheme) {
        case 'Default':
          addCss(`${process.env.VUE_APP_RES_URL}/theme/theme_default.css`)
          break
        case 'Eye':
          addCss(`${process.env.VUE_APP_RES_URL}/theme/theme_eye.css`)
          break
        case 'Gold':
          addCss(`${process.env.VUE_APP_RES_URL}/theme/theme_gold.css`)
          break
        case 'Night':
          addCss(`${process.env.VUE_APP_RES_URL}/theme/theme_night.css`)
          break
        default:
          addCss(`${process.env.VUE_APP_RES_URL}/theme/theme_default.css`)
      }
    },
    hideTitleAndMenu() {
      // this.$store.dispatch('setMenuVisible', false)
      this.setMenuVisible(false)
      // 将字号设置隐藏
      this.setSettingVisible(-1)
      this.setFontFamilyVisible(false)
    },
    // 章节切换与进度条同步
    refreshLocation() {
      // 里面是先获取当前的位置currentLocation，再获取当前的百分比设置好progress即可
      const currentLocation = this.currentBook.rendition.currentLocation()
      console.log(currentLocation)
      if (currentLocation && currentLocation.start) {
        const process = Math.floor(currentLocation.start.percentage * 100)
        this.setProgress(process)
        //   获取当前的位置 并存储到 localStorage中
        const startCfi = currentLocation.start.cfi
        console.log(startCfi)
        saveLocation(this.fileName, startCfi)
        // 判断书签
        const bookmark = getBookmark(this.fileName)
        if (bookmark) {
          if (bookmark.some(item => item.cfi === startCfi)) {
            this.setIsBookmark(true)
          } else {
            this.setIsBookmark(false)
          }
        } else {
          this.setIsBookmark(false)
        }
        console.log(bookmark)
        if (this.pagelist) {
          const totalPage = this.pagelist.length
          const currentPage = currentLocation.start.location
          if (currentPage && currentPage > 0) {
            this.setPaginate(currentPage + ' / ' + totalPage)
          } else {
            this.setPaginate('')
          }
        } else {
          this.setPaginate('')
        }
      }
    },
    // display方法  callback回调函数
    display(target, callback) {
      if (target) {
        this.currentBook.rendition.display(target).then(() => {
          this.refreshLocation()
          if (callback) callback()
        })
      } else {
        this.currentBook.rendition.display().then(() => {
          this.refreshLocation()
          if (callback) callback()
        })
      }
      const location = getLocation(this.fileName)
      console.log(location)
    },
    // 显示阅读时间
    getReadTimeText() {
      return this.$t('book.haveRead').replace('$1', getReadTimeByMinute(this.fileName))
    },
    showTotal() {
      const total = getBookmark(this.fileName)
      console.log('total', total)
      return total
    }
  }
}
